import { createRouter, createWebHistory } from 'vue-router'
import type { MyRouterItemArr } from "~/router"

// 静态引入框架页面
import Layout from "@/layout/Layout.vue"
import { el } from 'element-plus/es/locales.mjs'

const routes: MyRouterItemArr = [
  {
    path: '/',
    redirect: "/login"
  },
  // 登录
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue')
  },
  // 首页
  {
    path: '/home',
    name: 'home',
    component: Layout,
    meta: { path: "/home", title: "后台首页" },
    children: [
      {
        path: "/home",
        component: () => import("@/views/home/index.vue")
      }
    ]
  },
  // 用户管理
  {
    path: '/user',
    name: 'user',
    component: Layout,
    meta: { path: "/user", title: "用户管理" },
    redirect: "/user/list",
    children: [
      {
        path: "/user/list",
        meta: { path: "/user/list", title: "用户列表" },
        component: () => import("@/views/user/user-list.vue")
      },
      {
        path: "/user/add",
        meta: { path: "/user/add", title: "添加用户" },
        component: () => import("@/views/user/user-add.vue")
      },
      {
        path: "/user/mine",
        meta: { path: "/user/mine", title: "个人中心" },
        component: () => import("@/views/user/user-mine.vue")
      },
    ]
  },
  // 文章管理
  {
    path: '/article',
    name: 'article',
    component: Layout,
    meta: { path: "/article", title: "文章管理" },
    redirect: "/article/list",
    children: [
      {
        path: "/article/list",
        meta: { path: "/article/list", title: "文章列表" },
        component: () => import("@/views/article/article-list.vue")
      },
      {
        path: "/article/edit",
        meta: { path: "/article/edit", title: "文章编辑" },
        component: () => import("@/views/article/article-edit.vue")
      }
    ]
  },
  // excel管理
  {
    path: '/excel',
    name: 'excel',
    component: Layout,
    meta: { path: "/excel", title: "excel管理" },
    redirect: "/excel/import",
    children: [
      {
        path: "/excel/import",
        meta: { path: "/excel/import", title: "excel导入" },
        component: () => import("@/views/excel/excel-import.vue")
      },
      {
        path: "/excel/export",
        meta: { path: "/excel/export", title: "excel导出" },
        component: () => import("@/views/excel/excel-export.vue")
      }
    ]
  },
  // 404页面
  {
    path: '/404',
    component: () => import("@/views/404/index.vue")
  },
  // 404重定向
  {
    // 注意：vue2是path:"*"
    //       vue3是path:"/:catchAll(.*)"
    path: "/:catchAll(.*)",
    redirect: "/404",

  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由导航守卫
router.beforeEach((to, from, next) => {
  if(to.path==="/login"){
    next();
  }else{
    let token=localStorage.getItem("token");
    if(token === null || token===""){
      next("/login");
    }else{
      next();
    }
  }
})
export default router
